//
//  LawyerViewController.m
//  Unicorn
//
//  Created by xalo on 16/5/3.
//  Copyright © 2016年 bhj_jun. All rights reserved.
//

#import "LawyerViewController.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "LocationWithMapViewController.h"
@interface LawyerViewController ()<SDCycleScrollViewDelegate,AMapLocationManagerDelegate,AMapSearchDelegate>

@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSMutableArray *imageArray;
@property (nonatomic,strong)NSMutableArray *titleArray;
@property (nonatomic,retain)NSMutableDictionary *parameter;// 参数
@property (nonatomic,retain)AMapLocationManager *locationManager;
@property (nonatomic,retain)AMapSearchAPI *search;
@property (nonatomic,retain)NSString *userProvince;
@property (nonatomic,retain)NSString *userCity;
@property (nonatomic,retain)CLLocation *userLocation;


@end

@implementation LawyerViewController

#pragma mark - 懒加载
-(NSMutableArray *)imageArray{

    if (!_imageArray) {
        _imageArray=[NSMutableArray new];
    }
    return _imageArray;
}


-(NSMutableArray *)dataArray{

    if (!_dataArray) {
        _dataArray=[NSMutableArray new];
    }
    return _dataArray;
}

-(NSMutableArray *)titleArray{

    if (!_titleArray) {
        _titleArray=[NSMutableArray new];
    }
    return _titleArray;
}

-(NSMutableDictionary *)parameter{

    if (!_parameter) {
        _parameter=[NSMutableDictionary dictionaryWithDictionary:@{@"dtype":@"json",@"key":@"92b2b15418072f1597cc9de8f65f5048",@"count":@20,@"st":@0,@"city":@"西安"}];
    }
    return _parameter;
}





#pragma mark - 点击方法
// 创建按钮
-(void)createButtonWithFrame:(CGRect)frame title:(NSString *)title selector:(SEL)selector{
    
    UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:title forState:UIControlStateNormal];
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor=[UIColor yellowColor];
    button.layer.cornerRadius=20;
    button.layer.masksToBounds=YES;
    [button setFrame:frame];
    [self.view addSubview:button];
}

-(void)findLawyerWithArea:(UIButton *)sender{

    LawyerListViewController *listVC=[[LawyerListViewController alloc]init];
    listVC.cityName=self.userCity;
    listVC.proName=self.userProvince;
    [self.navigationController pushViewController:listVC animated:YES];
}


-(void)locationLawyer:(UIButton *)sender{


    NSLog(@"律师定位");
//    跳转到地图页面
    LocationWithMapViewController *locationVC =[[LocationWithMapViewController alloc]init];
    locationVC.userCity=self.userCity;
    locationVC.userLocation =self.userLocation;
    locationVC.lawyerDataArr= self.dataArray;
    
    [self.navigationController pushViewController:locationVC animated:YES];
    
    
}


//-(void)myselfLocation:(UIBarButtonItem *)sender{
//    
//    [AMapLocationServices sharedServices].apiKey =@"6e27217c4c2758773222518ae8c00b5c";
//    
//    // 带逆地理信息的一次定位（返回坐标和地址信息）
//    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
//    //   定位超时时间，可修改，最小2s
//    self.locationManager.locationTimeout = 3;
//    //   逆地理请求超时时间，可修改，最小2s
//    self.locationManager.reGeocodeTimeout = 3;
//    // 带逆地理（返回坐标和地址信息）
//    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
//        
//        if (error)
//        {
//            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
//            
//        }
//        
//        NSLog(@"location:%@", location);
//        
//        NSLog(@"%f,%f",location.coordinate.latitude,location.coordinate.longitude);
//        //配置用户Key  逆地理编码
//        [AMapSearchServices sharedServices].apiKey = @"6e27217c4c2758773222518ae8c00b5c";
//        
//        //初始化检索对象
//        _search = [[AMapSearchAPI alloc] init];
//        _search.delegate = self;
//        
//        
//        //构造AMapReGeocodeSearchRequest对象
//        AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
//        regeo.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude       longitude:location.coordinate.longitude];
//        regeo.radius = 10000;
//        regeo.requireExtension = YES;
//        
//        //发起逆地理编码
//        [_search AMapReGoecodeSearch: regeo];
//        
//        //        if (regeocode)
//        //        {
//        //            NSLog(@"reGeocode:%@", regeocode);
//        //        }
//    }];
//}

-(void)myLocation{
    
    [AMapLocationServices sharedServices].apiKey =KmapAppKey;
    
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，可修改，最小2s
    self.locationManager.locationTimeout = 3;
    //   逆地理请求超时时间，可修改，最小2s
    self.locationManager.reGeocodeTimeout = 3;
    // 带逆地理（返回坐标和地址信息）
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
        }
        self.userLocation =location;
        NSLog(@"location:%@", location);
        
        NSLog(@"%f,%f",location.coordinate.latitude,location.coordinate.longitude);
        //配置用户Key  逆地理编码
        [AMapSearchServices sharedServices].apiKey = KmapAppKey;
        
        //初始化检索对象
        _search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
        
        
        //构造AMapReGeocodeSearchRequest对象
        AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
        regeo.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude       longitude:location.coordinate.longitude];
        regeo.radius = 10000;
        regeo.requireExtension = YES;
        
        //发起逆地理编码
        [_search AMapReGoecodeSearch: regeo];
        
                if (regeocode)
                {
                    NSLog(@"reGeocode:%@", regeocode);
                }
    }];
    
}

#pragma mark - ----  实现逆地理编码的回调函数 ----

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if(response.regeocode != nil)
    {
        //通过AMapReGeocodeSearchResponse对象处理搜索结果
        //        NSString *result = [NSString stringWithFormat:@"ReGeocode: %@", response.regeocode];
        self.userProvince =response.regeocode.addressComponent.province;
        self.userCity=response.regeocode.addressComponent.city;
        self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:self.userCity style:UIBarButtonItemStylePlain target:self action:nil];
        
        NSLog(@"我的地理位置为---%@,%@",self.userProvince,self.userCity);
    }
}



#pragma mark - 数据请求
-(void)fetchDataWithparameter:(NSDictionary *)parameter url:(NSString *)urlStr{
    
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    [manager GET:urlStr parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSArray *resultArray=dic[@"result"];
        for (NSDictionary *mDic in resultArray) {
            
            if (![mDic[@"img"] hasSuffix:@".gif"]) {
                LawyerModel *model=[[LawyerModel alloc]init];
                [model setValuesForKeysWithDictionary:mDic];
                [self.dataArray addObject:model];
                [self.imageArray addObject:model.img];
                NSString *str=[model.name stringByAppendingString:[NSString stringWithFormat:@"                       %@",model.corp]];
                [self.titleArray addObject:str];
            }
        }
        // 创建轮播图
        [self createScrollView];
        //        NSLog(@"数据请求成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"数据请求失败");
    }];
}





#pragma mark - 视图生命周期


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title=@"律师";
    
    [self createButtonWithFrame:CGRectMake(20, 500, kWidth-40, 40) title:@"查找律师" selector:@selector(findLawyerWithArea:)];
    [self createButtonWithFrame:CGRectMake(20, 560, kWidth-40, 40) title:@"律师定位" selector:@selector(locationLawyer:)];
    //    初始化定位对象
    [AMapLocationServices sharedServices].apiKey =KmapAppKey;
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    
    self.userCity=@"西安";
    self.userProvince=@"陕西";
    [self myLocation];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:self.userCity style:UIBarButtonItemStylePlain target:self action:nil];
    
    NSString *cityUrl=@"http://op.juhe.cn/lawyers/city";
    [self.parameter setValue:self.userCity forKey:@"city"];
    [self fetchDataWithparameter:self.parameter url:cityUrl];
    
    // 创建label
     [self createLabel];
}


// 创建轮播图
-(void)createScrollView{

    SDCycleScrollView*headView=[SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 64, kWidth, kHeight/5*2) imageNamesGroup:self.imageArray];
    headView.titlesGroup=self.titleArray;
    headView.showPageControl=NO;
    headView.titleLabelTextColor=[UIColor cyanColor];
    headView.delegate=self;
    [self.view addSubview:headView];
}

// 点击图片回调
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{

    LawyerDetailViewController *detailVC=[[UIStoryboard storyboardWithName:@"Lawyer" bundle:nil]instantiateViewControllerWithIdentifier:@"LawyerVC"];
    detailVC.model=self.dataArray[index];
    [self.navigationController pushViewController:detailVC animated:YES];
}


// 创建一个label
-(void)createLabel{

    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 220, kWidth, kHeight-kHeight*0.4)];
    label.text=@"       守法爱民，知法护身。便民律师，旨在为您提供便捷的法律参考以及咨询功能。普及法律知识，增加您的法律意识，维权意识，保障您的合法权益不受侵犯。";
    label.textAlignment=NSTextAlignmentNatural;
    label.numberOfLines=0;
    label.backgroundColor=[UIColor cyanColor];
    label.font=[UIFont fontWithName:@"Arial" size:22];
    label.alpha=0.2;
    [self.view addSubview:label];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
